# -*- coding: utf-8 -*-

# -------------------------------
# Author    : linlingwei
# Email     : 951035650@qq.com
# File Name : t7.py
# Date      : 2020/4/2 
# IDE       : PyCharm
# Version   : 1.0.1
# -------------------------------


# 主要是需要moviepy这个库
import sys,os,shutil
import glob
from logging import DEBUG, INFO, basicConfig, getLogger
import subprocess
import traceback

mu_org_path = r"/storage/emulated/0/Android/data/com.xiaomi.smarthome/files/310733424"

root_path = r"E:\xiaomi\310733424"
dir_list = os.listdir(root_path)
output = []

for dl in dir_list:
    c_path = os.path.join(root_path, dl)
    c_list = os.listdir(os.path.join(root_path, dl))
    i = 0
    
    for cl in c_list:
        if ".mp4" in cl:
            i += 1
        if "_plain.m3u8" in cl:
            mu = cl
    
    if not i:
        if os.path.isfile(c_path):  # 判断该文件是否为文件或者文件夹
            os.remove(c_path)  # 若为文件，则直接删除
            print(str(c_path) + " removed!")
        elif os.path.isdir(c_path):
            shutil.rmtree(c_path, True)  # 若为文件夹，则删除该文件夹及文件夹内所有文件
            print("dir " + str(c_path) + " removed!")
    
    else:
        mu_path = os.path.join(c_path, mu)
        if os.path.exists(mu_path):
            
            _org_path = os.path.join(mu_org_path, dl).replace("\\", "/")
            
            fs = open(mu_path)
            data_line = fs.readlines()
            index = []
            for _line in data_line:
                if _org_path in _line:
                    idx = _line.replace(_org_path, c_path).rsplit("\n", 1)[0]
                    index.append(idx)
                    output.append(idx)
            fs.close()
            
        
        else:
            # print mu_path
            pass
        
        # ====
        print "================"
        output_path = os.path.join(r"E:\xiaomi\output1", dl + ".mp4")
        file_name_list = index
        first_file_name = file_name_list[0]
        temp_file_path = os.path.join(r"E:\xiaomi\output1", dl + ".txt")
        merge_file_path = output_path
        # print first_file_name
        print temp_file_path
        print merge_file_path

        try:
            with open(temp_file_path, 'w') as f2:
                for file_name in file_name_list:
                    # f2.write("file  " + file_name + "\n")
                    f2.write('file  "{}"\n'.format(file_name))

        except Exception as e:
            raise Exception()


        # cmd = "ffmpeg -f concat -loglevel error -safe 0 -i " + temp_file_path + " -g 10 -s 640*340 -q 20 -c -copy " + merge_file_path
        cmd = "ffmpeg -f concat -i {} -vcodec libx264 -threads 4 -codec copy {}".format(temp_file_path,merge_file_path)
        print cmd
        # "ffmpeg -f concat -i input.txt -codec copy output.mp4"
        try:
            proc = subprocess.Popen(cmd, shell=1,
                                                         stdout=subprocess.PIPE,
                                                         stderr=subprocess.STDOUT)

            out, err = proc.communicate()
            print out, err
        except Exception as e:
            raise Exception()
        finally:
            pass
            # if os.path.exists(temp_file_path):
            #     os.remove(temp_file_path)

if __name__ == '__main__':
    pass